package com.qf.service.impl;

import com.qf.dao.UserRepository;
import com.qf.pojo.BaseResult;
import com.qf.pojo.TbUser;
import com.qf.service.UserService;
import com.qf.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * Created by 54110 on 2021/4/30.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserRepository  userRepository;

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    JwtUtils jwtUtils;

    @Value("${spring.mail.username}")
    private String from;
    @Override
    public BaseResult validaUserName(String userName) {
        TbUser byUserName = userRepository.findByUserName(userName);
        if (byUserName!=null){
            return new BaseResult(1,"用户名以重复");
        }
        return new BaseResult(0,"用户名未被占用");
    }

    @Override
    public BaseResult validaEmail(String email) {
        TbUser byUserName = userRepository.findByEmail(email);
        if (byUserName!=null){
            return new BaseResult(1,"邮箱已被占用");
        }
        return new BaseResult(0,"邮箱未被占用");
    }

    @Override
    public BaseResult sendMail(Object email) {

        TbUser byUserName = userRepository.findByEmail((String)email);
        if (byUserName!=null){
            return new BaseResult(1,"邮箱已被占用");
        }
        //就可以走发送邮件 的逻辑
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setTo((String)email);
        simpleMailMessage.setSubject("千锋互联验证码");
        //随机生成
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        for (int i=0;i<4;i++){
            stringBuffer.append(random.nextInt(10));
        }
        simpleMailMessage.setText(stringBuffer.toString());
        javaMailSender.send(simpleMailMessage);
        //将验证码存储到redis中
        redisTemplate.opsForValue().set((String)email,stringBuffer.toString());
        return new BaseResult(0,"发送成功！");
    }

    @Override
    public BaseResult registry(TbUser tbUser) {
        //从redis中获取验证码
        String o =(String) redisTemplate.opsForValue().get(tbUser.getEmail());
        if (o!=null&&!o.equals(tbUser.getCode())){
            return new BaseResult(1,"验证码不一致！");
        }
        //执行添加
        TbUser save = userRepository.save(tbUser);
        if (save==null){
            return new BaseResult(1,"注册失败！");
        }

        return new BaseResult(0,"注册成功！");
    }

    @Override
    public BaseResult login(TbUser tbUser) {

        TbUser user = userRepository.findByUserName(tbUser.getUserName());

        if (user==null){
            return new BaseResult(1,"没有该用户，请先注册！");
        }
        if (!user.getPassword().equals(tbUser.getPassword())){
            return new BaseResult(1,"密码输入错误！");
        }
        //登录成功后，需要放置在reids中 key应为 唯一值，value设置为 用户对象
        //UUID uuid = UUID.randomUUID();
        //接下来放置在redis中 防止在redis中时转为 json格式
        //String string = JSONObject.toJSONString(byUserName);
        //redisTemplate.opsForValue().set(uuid.toString(),string);

        //引入Jwt生成token
        Map map = new HashMap<>();
        map.put("username",user.getUserName());
        map.put("id",user.getId());
        String token = jwtUtils.createToken(map);
        return new BaseResult(0,"登录成功！",token);
    }
}
